<?php


namespace app\common\behavior;

use app\common\library\AlipayFundService;
use app\common\library\UserUpdateLib;
use app\common\library\WechatChapter;
use app\common\model\ChargingGun;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\OrderBalancePay;
use app\common\model\User;
use app\common\model\UserGiveMoneyLog;
use app\common\model\WechatChapterOrder;
use think\Db;
use think\Exception;

/**
 * 微信免押 支付宝免押 支付类
 * Class WechatPayScorePay
 * @package app\common\behavior
 */
class WechatPayScorePay
{
    /**
     * 免押支付
     * @param $param
     * @throws Exception
     */
    public function handelWechatPayScorePay(&$param)
    {
        /**
         * 保存错误日志
         * @param $msg
         * @param $orderId
         */
        $saveErrorInfo = function ($msg, $orderId) {
            //记录充电报错日志
            //trace("==========================余额充电支付行为处理---开始========================", 'error');
            trace("========================开始处理结束订单8-3-28-6 免押支付异常==============================");
            $data['order_id'] = $orderId;
            $data['error_msg'] = $msg;
            //trace($data, 'error');
            trace("========================开始处理结束订单8-3-28-7 免押支付异常==============================" . json_encode($data));
            trace("==========================余额充电支付行为处理---结束========================", 'error');
        };
        $chapter_order_id = $param['order_id'];
        $total_money = $param['deduction_fee'];
        //$total_money = 0.01;//yss临时
        trace("========================开始处理结束订单8-3-28-1============================== 免押记录id：{$chapter_order_id} ============ 免押扣款金额：{$total_money}");
        //Db::startTrans();
        try {
            $wechatChapterOrderInfo = WechatChapterOrder::get(['id' => $chapter_order_id]);
            if (!$wechatChapterOrderInfo) {
                throw new Exception('暂无相关微信支付分订单');
            }
            trace("========================开始处理结束订单8-3-28-2============================== 免押记录：" . json_encode($wechatChapterOrderInfo));
            if ($wechatChapterOrderInfo->state == 'DOING'){
                if ($wechatChapterOrderInfo->terminal == WechatChapterOrder::TERMINAL_WECHAT){//使用的微信免押
                    //调用结束订单
                    $wechatChapter = new WechatChapter();
                    $description="租赁费用{$total_money}元,日封顶69元,总封顶99元";
                    trace("========================开始处理结束订单8-3-28-2 调用免押支付前=============================={$wechatChapterOrderInfo['out_order_no']}============{$total_money}============{$description}");
                    $result=$wechatChapter->completeOrder($wechatChapterOrderInfo['out_order_no'], '', $total_money,$description);
                    trace("========================开始处理结束订单8-3-28-3 调用免押接口扣款执行结果==============================" . json_encode($result));
                    if($result['status']==0){
                        throw new Exception($result['msg']);
                    }
                }elseif ($wechatChapterOrderInfo->terminal == WechatChapterOrder::TERMINAL_ALIPAY){//使用的支付宝免押
                    $outtrade_no = WechatChapterOrder::createOuttradeNo();
                    $result = AlipayFundService::payWithAuth($outtrade_no, $total_money, '台球杆租赁费用', $wechatChapterOrderInfo->auth_no, 'PREAUTH_PAY', 'COMPLETE');

                }
                trace("========================开始处理结束订单8-3-28-4 开始修改免押支付记录id==============================");
                $wechatChapterOrderInfo->total_money = $total_money;
                $wechatChapterOrderInfo->state='DONE';
                $wechatChapterOrderInfo->save();
                trace("========================开始处理结束订单8-3-28-5 完成修改免押支付记录id==============================");
            }
            //Db::commit();
        } catch (Exception $e) {
            //Db::rollback();
            $saveErrorInfo($e->getMessage().$e->getTraceAsString(), $param['order_id']);
            throw $e;
        } catch (\Exception $e) {
            Db::rollback();
            $saveErrorInfo($e->getMessage().$e->getTraceAsString(), $param['order_id']);
            throw $e;
        }
    }


    /**
     * 取消免押支付
     */
    public function handelWechatPayScoreCancel(&$param)
    {
        /**
         * 保存错误日志
         * @param $msg
         * @param $orderId
         */
        $saveErrorInfo = function ($msg, $orderId) {
            //记录充电报错日志
            trace("==========================余额充电支付行为处理---开始========================", 'error');
            $data['order_id'] = $orderId;
            $data['error_msg'] = $msg;
            trace($data, 'error');
            trace("==========================余额充电支付行为处理---结束========================", 'error');
        };

        Db::startTrans();
        try {
            $wechatChapterOrderInfo = WechatChapterOrder::get(['id' => $param['order_id']]);
            if (!$wechatChapterOrderInfo) {
                throw new Exception('暂无相关微信支付分订单');
            }
            if ($wechatChapterOrderInfo->terminal == WechatChapterOrder::TERMINAL_WECHAT){//微信免押
                //调用取消订单
                $wechatChapter = new WechatChapter();
                $result=$wechatChapter->tocancelwxfreeorder($wechatChapterOrderInfo['out_order_no'], '订单未产生金额,取消订单');
                trace('========================租赁失败开始取消免押-1反馈调用接口数据==============================' . json_encode($result));
                if(isset($result['status'])&&$result['status']==0){
                    throw new Exception($result['msg']);
                }
            }elseif ($wechatChapterOrderInfo->terminal == WechatChapterOrder::TERMINAL_ALIPAY){//支付宝免押
                // 调用解冻接口
                $outRequestNo = date('YmdHis')  . mt_rand(10000, 99999) . mt_rand(100, 999);
                $result = AlipayFundService::unfreezeAuthOrder($wechatChapterOrderInfo->auth_no, $outRequestNo, $wechatChapterOrderInfo->alipay_amount, '支付宝免押取消');
            }

            $wechatChapterOrderInfo->total_money = 0;
            $wechatChapterOrderInfo->state='REVOKED';
            $wechatChapterOrderInfo->save();

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $saveErrorInfo($e->handelWechatPayScoreCancel().$e->getTraceAsString(), $param['order_id']);
            throw $e;
        } catch (\Exception $e) {
            Db::rollback();
            $saveErrorInfo($e->getMessage().$e->getTraceAsString(), $param['order_id']);
            throw $e;
        }
    }

}